package com.kaka.controller;

import com.kaka.bean.Result;
import com.kaka.bean.Student;
import com.kaka.bean.Teacher;
import com.kaka.util.MyJDBCUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import net.sf.json.JSONArray;

import java.io.IOException;
import java.util.List;

@WebServlet(name = "teacherController", value = "/teacher")
public class TeacherController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer currentPage = Integer.valueOf(req.getParameter("currentPage"));
        Integer pageSize = Integer.valueOf(req.getParameter("pageSize"));
        HttpSession session = req.getSession();
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        /*System.out.println(teacher);
        System.out.println(teacher.getTid());*/
        int tid = teacher.getTid();

        if (currentPage == null && pageSize == null) {
            currentPage = 1;
            pageSize = 10;
        }

        String sql1 = "select * from student where tid = ?";
        String sql2 = "select * from student where tid = ? limit ?,?";

        List<Student> admins1 = MyJDBCUtil.dqlSQL(Student.class, sql1, tid);
        List<Student> admins2 = MyJDBCUtil.dqlSQL(Student.class, sql2, tid,(currentPage - 1) * pageSize, pageSize);
        Result.success(req, resp, JSONArray.fromObject(admins2), admins1.size());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String sid = req.getParameter("sid");
        String score = req.getParameter("score");
        //System.out.println(sid + ":" + score);
        String sql = "update student set score = ? where sid = ?";
        int i = MyJDBCUtil.dmlSQL(sql, score, sid);
        if (i == 1) {
            Result.success(req, resp);
        } else {
            Result.error(req, resp);
        }
    }
}
